package login.Controller.userInformation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import login.Model.dao.DBUtil;
import login.Model.dao.JsonUtil;
import login.Model.dao.SendMail;
import login.Model.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(name = "mailboxServlet",value = "/mailbox")
public class mailboxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转化成String类
        String jsonString = String.valueOf(JsonUtil.getJson(req));
        //转换成JSONObject类
        JSONObject jsonObject = JSON.parseObject(jsonString);
        //获取信息
        String name = jsonObject.getString("name"); //姓名
        String postbox = jsonObject.getString("postbox"); //邮箱

        //put方法：设置一个json中的属性
        //status表示给前端的状态值
        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();

        /**
         * 邮箱找回密码
         */
        try {
            if(UserService.judgeMailbox(name, postbox)){
                SendMail mySendMail = new SendMail();
                mySendMail.sendMail(postbox,UserService.getInformation(name));
            }else {
                object.put("code", -1);
                object.put("message", "用户信息输入有误，请重试");
                out.println(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                DBUtil.freeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
